package dubbo.learn.registry.redis;

import dubbo.learn.common.ProviderHostAndPort;
import dubbo.learn.common.RpcContext;
import dubbo.learn.common.contract.cluster.ClusterLayerRpcInvoker;
import dubbo.learn.common.contract.registry.RegistryLayerRpcInvoker;
import dubbo.learn.common.spi.SpiServiceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class RedisRegistryRpcInvoker implements RegistryLayerRpcInvoker {

    @Autowired
    private RedisRegistry redisRegistry;


    @Override
    public Object invoke(RpcContext rpcContext) {
        ClusterLayerRpcInvoker clusterLayerRpcInvoker = SpiServiceLoader.loadService(ClusterLayerRpcInvoker.class);
        List<ProviderHostAndPort> list = redisRegistry.getServiceProviderList(rpcContext.getServiceName());
        if (CollectionUtils.isEmpty(list)) {
            throw new RuntimeException();
        }

        Object o = clusterLayerRpcInvoker.invoke(list, rpcContext);
        return o;
    }
}
